package cn.sumpu.app.guoguojie.biz.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cn.sumpu.app.guoguojie.biz.CommentBiz;
import cn.sumpu.app.guoguojie.biz.DoingBiz;
import cn.sumpu.app.guoguojie.biz.DoingLoveBiz;
import cn.sumpu.app.guoguojie.biz.DoorplateBiz;
import cn.sumpu.app.guoguojie.biz.FamilyBiz;
import cn.sumpu.app.guoguojie.biz.IdentifierBiz;
import cn.sumpu.app.guoguojie.biz.MailBiz;
import cn.sumpu.app.guoguojie.biz.MemberBiz;
import cn.sumpu.app.guoguojie.biz.MentionBiz;
import cn.sumpu.app.guoguojie.biz.MessageBiz;
import cn.sumpu.app.guoguojie.constant.FamilyRole;
import cn.sumpu.app.guoguojie.constant.OwnerType;
import cn.sumpu.app.guoguojie.constant.Sex;
import cn.sumpu.app.guoguojie.dao.MemberDetailDao;
import cn.sumpu.app.guoguojie.dao.FamilyDao;
import cn.sumpu.app.guoguojie.dao.MemberDao;
import cn.sumpu.app.guoguojie.domain.Comment;
import cn.sumpu.app.guoguojie.domain.Doing;
import cn.sumpu.app.guoguojie.domain.MemberDetail;
import cn.sumpu.app.guoguojie.domain.Family;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.DateUtil;
import cn.sumpu.app.guoguojie.util.DoorplateGenerator;
import cn.sumpu.app.guoguojie.util.Experience;
import cn.sumpu.app.guoguojie.util.PageModel;

public class FamilyBizImpl implements FamilyBiz {

	private FamilyDao familyDao;
	private MemberDao memberDao;
	private MemberDetailDao memberDetailDao;
	@Autowired
	private DoorplateBiz doorplateBiz;
	@Autowired
	private MessageBiz messageBiz;
	private MailBiz mailBiz;
	@Autowired
	private MentionBiz mentionBiz;
	@Autowired
	private MemberBiz memberBiz;
	@Autowired
	private DoingBiz doingBiz;
	@Autowired
	private DoingLoveBiz doingLoveBiz;
	@Autowired
	private CommentBiz commentBiz;
	@Resource
	private IdentifierBiz identifierBiz;
	
	

	public void setMemberDetailDao(MemberDetailDao memberDetailDao) {
		this.memberDetailDao = memberDetailDao;
	}

	public void setFamilyDao(FamilyDao familyDao) {
		this.familyDao = familyDao;
	}

	public void setMemberDao(MemberDao memberDao) {
		this.memberDao = memberDao;
	}

	public void setMailBiz(MailBiz mailBiz) {
		this.mailBiz = mailBiz;
	}
	
	public void myFamily(Integer page ,HttpServletRequest request)throws AppBusinessException {
		Member member = (Member) request.getSession().getAttribute("member");
		String familyId = member.getFamily();
		Family family = getFamilyByDoor(familyId);
		request.getSession().setAttribute("family", family);
		//int count = messageBiz.messageAllNoReadCount(familyId);
		int doingCount = doingBiz.getDoingListCount(familyId);
		int mentionCount = mentionBiz.getMentionCount(familyId);
		List<Member> memberList = memberBiz.getMemberListByDoorplate(familyId);
		request.getSession().setAttribute("memberList", memberList);
		request.setAttribute("mentionCount",Common.getCountFormat(mentionCount));
		request.setAttribute("doingCount", doingCount);
		//request.setAttribute("messageNoRead",Common.getCountFormat(count));
		// 清除session里面存的taFamily属性（标识是回到我家了）
		request.getSession().removeAttribute("taFamily");
		
//		账号是否已经激活
		request.setAttribute("isActive",
				memberBiz.getMemberById(member.getIdentifier())
						.getIsActive());
//		微博数据
		doingBiz.enterWeiBo("family", request);
		doingBiz.followDoingList(page, request);
	}
	
	public void myFamilyLeft(HttpServletRequest request)throws AppBusinessException {
		Member member = (Member) request.getSession().getAttribute("member");
		String familyId = member.getFamily();
		Family family = getFamilyByDoor(familyId);
		request.getSession().setAttribute("family", family);
		// count = messageBiz.messageAllNoReadCount(familyId);
		int doingCount = doingBiz.getDoingListCount(familyId);
		int mentionCount = mentionBiz.getMentionCount(familyId);
		List<Member> memberList = memberBiz.getMemberListByDoorplate(familyId);
		request.getSession().setAttribute("memberList", memberList);
		request.setAttribute("mentionCount",Common.getCountFormat(mentionCount));
		request.setAttribute("doingCount", doingCount);
		//request.setAttribute("messageNoRead",Common.getCountFormat(count));
		// 清除session里面存的taFamily属性（标识是回到我家了）
		request.getSession().removeAttribute("taFamily");
		
//		账号是否已经激活
		request.setAttribute("isActive",
				memberBiz.getMemberById(member.getIdentifier())
						.getIsActive());

	}
	
	


	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public String register(Family family, Member member)
			throws AppBusinessException {
		String doorplate = DoorplateGenerator.createDoorplate();
		family.setDoorplate(doorplate);
		family.setIsActive(true);
		member.setFamily(doorplate);
		String passwd = member.getPassword();
		String salt = Common.getRandStr(6, false);
		member.setSalt(salt);
		member.setPassword(Common.md5(Common.md5(passwd)));
		String identifier = identifierBiz.generateId("member");
		member.setIdentifier(identifier);
		familyDao.insert(family);
		memberDao.insert(member);
		MemberDetail detail = new MemberDetail();
		detail.setMember(member.getIdentifier());
		detail.setEmail(member.getEmail());
		memberDetailDao.insertMemberDetail(detail);
		return doorplate;
	}

	@Override
	public Family getFamilyByDoor(String doorplate) throws AppBusinessException {
		if(Common.emptyStr(doorplate)){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>(); 
		map.put("doorplate", doorplate);  
		List<Family> fList = familyDao.getFamilyList(map);
		if (fList != null && fList.size() > 0){
			int loveCount=doingLoveBiz.getMyFamilyLoveAmount(doorplate);
			int fansCount=doingBiz.getFansCount(doorplate);
			int followCount=doingBiz.getFollowCount(doorplate);
			Family family=fList.get(0);
			family.setLoveCount(loveCount);
			family.setFansCount(fansCount);
			family.setFollowCount(followCount);
			//获取徽章
			getMyBadge(family);
			return family;
		}
			
		return null;
	}

	private void getMyBadge(Family family) throws AppBusinessException {
		String reward=family.getRookieReward(); 
		String familyId=family.getDoorplate();
		//5、获取"我爱社交"徽章
		if(reward.charAt(5)=='0'){
			int myComCount=commentBiz.getMyComCount(familyId);
			if(myComCount>=10){
				reward = reward.replaceAll("(\\d{5})(0)(\\d{9})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
		//6、获取"我有朋友"徽章
		if(reward.charAt(6)=='0'){
			int fansCount=family.getFansCount();
			if(fansCount>=5){
				reward = reward.replaceAll("(\\d{6})(0)(\\d{8})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
		//7、获取"有人喜欢"徽章
		if(reward.charAt(7)=='0'){
			int loveCount=family.getLoveCount();
			if(loveCount>=10){
				reward = reward.replaceAll("(\\d{7})(0)(\\d{7})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
		//8、获取"好喜欢呀"徽章
		if(reward.charAt(8)=='0'){
			int myLoveCount=doingLoveBiz.getMyLoveDoingCount(familyId); 
			if(myLoveCount>=100){
				reward = reward.replaceAll("(\\d{8})(0)(\\d{6})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
		//9、获取"分享高手"徽章
		if(reward.charAt(9)=='0'){ 
			int myProCount=doingBiz.getDoingProCount(familyId);
			if(myProCount>=50){
				reward = reward.replaceAll("(\\d{9})(0)(\\d{5})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
		//10、获取"图片分享"徽章
		if(reward.charAt(10)=='0'){
			int myPicCount=doingBiz.getDoingPicCount(familyId);
			if(myPicCount>=50){
				reward = reward.replaceAll("(\\d{10})(0)(\\d{4})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
		//11、获取"顶帖高手"徽章
		if(reward.charAt(11)=='0'){
			int myReplyCount=doingBiz.getMyRelpycCount(familyId);
			if(myReplyCount>=10){
				reward = reward.replaceAll("(\\d{11})(0)(\\d{3})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
		//13、获取"画报专家"徽章
		if(reward.charAt(13)=='0'){
			int count=doingBiz.getMyPictorialBadge(familyId);
			if(count>=5){
				reward = reward.replaceAll("(\\d{13})(0)(\\d{1})", "$11$3");
				family.setRookieReward(reward);
				updateFamily(family);
			}
		}
	}
	

	@Override
	public List<Family> getFamilyByNickname(String nickname)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("nickname", nickname);
		return familyDao.getFamilyList(map);
	}

	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void updateFamily(Family family) throws AppBusinessException {
		if(Experience.isOnce(family.getRookieReward(), 2)){
			family.setRookieReward(Experience.replaceRookieReward(family.getRookieReward(), 2));
		}
		familyDao.updateFamily(family);
	}

	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public Member register(String basePath, Family family, Member member,
			List<Member> babyList) throws AppBusinessException {
		String doorplate = family.getDoorplate();
		if(doorplateBiz.isVipDoorplate(doorplate)){
			Throwable throwable = new Throwable("门牌号是靓号#family_idx_doorplate");
			throw new AppBusinessException("门牌号是靓号",throwable);
		}
		String identifier = identifierBiz.generateId("member");

		family.setDoorplate(doorplate);
		family.setAvatar(Common.AVATAR_FAMILY_DEFALUT);
		familyDao.insert(family);   
		//建家成功加分
		updateFamilyIntegral(doorplate, Experience.createFamily, null);
		
//		将用过的门牌号更新为用过的
		doorplateBiz.updateDoorplate(doorplate);
		member.setFamily(doorplate);
		member.setIdentifier(identifier);
		member.setPassword(Common.md5(Common.md5(member.getPassword())));
		member.setActiveCode(Common.getRandStr(10, false));
		member.setIsHost(true);
		if (FamilyRole.FATHER.getValue().equals(member.getRole())) {
			member.setAvatar(Common.AVATAR_MAN_DEFALUT);
		}else if (FamilyRole.MOTHER.getValue().equals(member.getRole())) {
			member.setAvatar(Common.AVATAR_WOMAN_DEFALUT);
		}
		member.setOwner(member.getFamily());
		member.setOwnerType(OwnerType.FAMILY.getValue());
		memberDao.insert(member);

		member.setFamilyObj(family);
		//
		MemberDetail detailMember = new MemberDetail();
		detailMember.setProvince(family.getProvince());
		detailMember.setCity(family.getCity());
		detailMember.setMember(identifier);
		// 如果是妈妈角色则将性别是女，否则是男
		detailMember
				.setSex(FamilyRole.MOTHER.getValue().equals(member.getRole()) ? Sex.FEMALE
						.getValue() : Sex.MALE.getValue());
		memberDetailDao.insertMemberDetail(detailMember);

		member.setMemberDetail(detailMember);

		if (babyList != null && babyList.size() > 0) {
			for (Member baby : babyList) {
				String babyId = identifierBiz.generateId("member_detail");
				baby.setIdentifier(babyId);
				baby.setFamily(doorplate);
				baby.setRole(FamilyRole.BABY.getValue());
				baby.setAvatar(Common.AVATAR_BABY_DEFALUT);
				memberDao.insert(baby);
				MemberDetail detail = new MemberDetail();
				detail.setMember(babyId);
				detail.setSex(baby.getSex());
				detail.setBirthday(baby.getBirthday());
				memberDetailDao.insertMemberDetail(detail);
			}
		}
		
		mailBiz.sendEmail(basePath, member, null, null);
//		默认关注果果小家
		doingBiz.addFollow(family.getDoorplate(), "124773", member.getIdentifier());
		return member;
	}

	@Override
	public boolean activeMember(String memberId, String activeCode)
			throws AppBusinessException {
		Member originalM = memberDao.getMemberById(memberId);
		if (null != originalM && activeCode.equals(originalM.getActiveCode())) {
			Member updateM = new Member();
			updateM.setIdentifier(memberId);
			updateM.setIsActive(true);
			memberDao.updateMember(updateM);
			return true;
		}
		return false;
	}

	// 通过会员编号查询得到家的信息
	@Override
	public Family getFamilyByMember(String member) throws AppBusinessException {
		return familyDao.getFamilyByMember(member);
	}

	@Override
	public void updateFamilyIntegral(String doorplate, Integer point, String rookieReward)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("doorplate", doorplate);
		map.put("point", point);
		map.put("rookieReward", rookieReward);
		familyDao.updateFamilyIntegral(map);
	}

	@Override
	public void updateFamilyByLogin(String doorplate, Integer point,
			String isYesterday)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("doorplate", doorplate);
		map.put("point", point);
		map.put("yesterday", isYesterday);
		familyDao.updateFamilyByLogin(map);
	}

	//根据门牌号取得这家最近的两条微博(不是同一天发的)
	@Override
	public List<String> getDoingTwoDay(String doorplate)
			throws AppBusinessException {
		return familyDao.getDoingTwoDay(doorplate);
	}

	//根据门牌号取得这家最近的两篇日志(不是同一天发的)
	@Override
	public List<String> getBlogTwoDay(String doorplate)
			throws AppBusinessException {
		return familyDao.getBlogTwoDay(doorplate);
	}

	//根据门牌号取得这家今天发表了多少条微博（包括对别人微博的评论）
	@Override
	public int getDoingCommentCount(String doorplate)
			throws AppBusinessException {
		return familyDao.getDoingCommentCount(doorplate);
	}

	//根据门牌号取得这家今天发表了多少篇日志（包括对别人日志的评论）
	@Override
	public int getBlogCommentCount(String doorplate)
			throws AppBusinessException {
		return familyDao.getBlogCommentCount(doorplate);
	}

	//根据门牌号取得今天这家添加了几个邻居
	@Override
	public int getAddFriendCount(String doorplate) throws AppBusinessException {
		return familyDao.getAddFriendCount(doorplate);
	}

	//根据门牌号取得今天这家同意了几个邻居的邀请
	@Override
	public int getAgreeFriendCount(String doorplate)
			throws AppBusinessException {
		return familyDao.getAgreeFriendCount(doorplate);
	}

	//根据门牌号取得这家今天微博的最高评论量
	@Override
	public Comment getDoingTopCommentCount(String doorplate)
			throws AppBusinessException {
		return familyDao.getDoingTopCommentCount(doorplate);
	}

	//根据门牌号取得这家今天日志的最高评论量
	@Override
	public Comment getBlogTopCommentCount(String doorplate)
			throws AppBusinessException {
		return familyDao.getBlogTopCommentCount(doorplate);
	}

	/**
	 * author Bruce Zhang
	 * @param family	家的门牌号
	 * @param content	信息内容
	 * 发送系统消息
	 * @throws AppBusinessException
	 */
	@Override
	public void insertSystemMessage(String family, String content)
			throws AppBusinessException {
		//messageBiz.insertSystemMessage(family, content);
	}

	@Override
	public void myHomeRight(HttpServletRequest request)
			throws AppBusinessException {
		String family=""; 
		Member member=(Member) request.getSession().getAttribute("member"); 
		family=member.getFamily();
		Boolean isHasbabyBoolean=false;
		int followCount = doingBiz.getFollowCount(member.getFamily());
		int fansCount = doingBiz.getFansCount(member.getFamily()); 
		int loveCount=doingLoveBiz.getMyFamilyLoveAmount(family);
		request.setAttribute("followCount", followCount);
		request.setAttribute("fansCount", fansCount);
		request.setAttribute("loveCount", loveCount);
		request.setAttribute("isHasbabyBoolean", isHasbabyBoolean);
		int approveDateInterval=0;
		if(!Common.empty(member.getApproveDate())){
			approveDateInterval=DateUtil.daysOfTwo(member.getApproveDate(), new Date());
		}
		//达人申请被拒后相隔下次申请的天数
		request.setAttribute("approveDateInterval", approveDateInterval); 
		
	}
	
	

	@Override
	public void taHomeRight(HttpServletRequest request)
			throws AppBusinessException {
		String family = request.getParameter("family");
		int followCount = doingBiz.getFollowCount(family);
		int fansCount = doingBiz.getFansCount(family);
		int loveCount=doingLoveBiz.getMyLoveCount(family);
		request.setAttribute("followCount", followCount);
		request.setAttribute("fansCount", fansCount);
		request.setAttribute("loveCount", loveCount);
	}

	@Override
	public Family getFamilyObjById(String family) throws AppBusinessException {
		if(Common.empty(family)) return null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("doorplate", family);  
		List<Family> fList = familyDao.getFamilyList(map);
		if(fList != null && fList.size() > 0){
			Family familyObj = fList.get(0);
			List<Member> memberList = memberBiz.getMemberListByDoorplate(family);
			familyObj.setMemberList(memberList);
			return familyObj;
		}
		return null;
	}

	@Override
	public PageModel getLoveFamilyList(Integer pageSize, Integer page) throws AppBusinessException {
		if(Common.empty(page)){
			page=1;
		}
		if(pageSize==null || pageSize < 1){
			pageSize = 10;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		int count=familyDao.getLoveFamilyListCount(map);
		map.put("startId", (page-1)*pageSize);
		map.put("pageSize", pageSize);
		List<Family> list=familyDao.getLoveFamilyList(map);
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(list);
		pm.setPageSize(pageSize);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + pageSize - 1) / pageSize);
		return pm;
	}

	@Override
	public List<String> getAllFamilyId() throws AppBusinessException {
		return familyDao.getAllFamilyId();
	}
	
	

}
